package ui;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;

import handlers.ClientStatusHandler;

import model.jena.properties.FileItem;
import multicast.MulticastCommsClient;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import client.FileStoreClient;
import client.ProgressUpdater;

import com.cloudgarden.resource.SWTResourceManager;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResIterator;
import com.hp.hpl.jena.rdf.model.Resource;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FileStoreClientUI extends org.eclipse.swt.widgets.Composite implements ClientStatusHandler, ProgressUpdater{

	private Menu menu1;
	private MenuItem aboutMenuItem;
	private Button downloadStartButton;
	private TreeItem rootNode;
	private Tree fileDownloadTree;
	private Button cancelUploadButton;
	private Button resetUploadButton;
	private Button uploadFileButton;
	private Text fileUploadLocation;
	private Button fileUploadBrowserButton;
	private Label uploadFileBrowse;
	private Label progressUpdateBarLabel;
	private ProgressBar uploadProgressBar;
	private Composite composite1;
	private Composite uploadComp;
	private Menu helpMenu;
	private MenuItem helpMenuItem;
	private MenuItem exitMenuItem;
	private Menu fileMenu;
	private TabItem uploadFileTab;
	private Button updateFileButton;
	private Button deleteFileButton;
	private TabItem tabItem1;
	private TabFolder tabFolderComp;
	private Composite containerComp;
	private MenuItem connentMenuItem;
	private MenuItem fileMenuItem;
	private FileDialog fileDialog;
	private DirectoryDialog folderDialog;
	private FileStoreClient client;

	{
		//Register as a resource user - SWTResourceManager will
		//handle the obtaining and disposing of resources
		SWTResourceManager.registerResourceUser(this);
	}

	public FileStoreClientUI(Composite parent, int style) {
		super(parent, style);
		initGUI();
		client = new FileStoreClient();
		client.addStatusHandler(this);
		

	}
	public void addClient(FileStoreClient client){
		this.client = client;
	}
	/**
	* Initializes the GUI.
	*/
	private void initGUI() {
		try {
			this.setSize(new org.eclipse.swt.graphics.Point(400,300));
			this.setBackground(SWTResourceManager.getColor(192, 192, 192));
			FillLayout thisLayout = new FillLayout(org.eclipse.swt.SWT.HORIZONTAL);
			fileDialog = new FileDialog(this.getShell()) ;
			folderDialog = new DirectoryDialog(this.getShell());
			this.setLayout(thisLayout);
			{
				containerComp = new Composite(this, SWT.NONE);
				FillLayout containerCompLayout = new FillLayout(org.eclipse.swt.SWT.HORIZONTAL);
				containerComp.setLayout(containerCompLayout);
				{
					tabFolderComp = new TabFolder(containerComp, SWT.NONE);
					{
						tabItem1 = new TabItem(tabFolderComp, SWT.NONE);
						tabItem1.setText("Download File");
						{
							composite1 = new Composite(tabFolderComp, SWT.NONE);
							FormLayout composite1Layout = new FormLayout();
							composite1.setLayout(composite1Layout);
							tabItem1.setControl(composite1);
							{
								updateFileButton = new Button(composite1, SWT.PUSH | SWT.CENTER);
								FormData updateFileButtonLData = new FormData();
								updateFileButtonLData.left =  new FormAttachment(0, 1000, 162);
								updateFileButtonLData.top =  new FormAttachment(0, 1000, 242);
								updateFileButtonLData.width = 64;
								updateFileButtonLData.height = 23;
								updateFileButton.setLayoutData(updateFileButtonLData);
								updateFileButton.setText("Update");
								updateFileButton.setEnabled(false);
							}
							{
								deleteFileButton = new Button(composite1, SWT.PUSH | SWT.CENTER);
								FormData deleteFileButtonLData = new FormData();
								deleteFileButtonLData.left =  new FormAttachment(0, 1000, 96);
								deleteFileButtonLData.top =  new FormAttachment(0, 1000, 242);
								deleteFileButtonLData.width = 66;
								deleteFileButtonLData.height = 23;
								deleteFileButton.setLayoutData(deleteFileButtonLData);
								deleteFileButton.setText("Delete");
								deleteFileButton.setEnabled(false);
								deleteFileButton.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										TreeItem[] selectedItems = fileDownloadTree.getSelection();
										if(selectedItems != null && selectedItems.length == 1){
											client.sendDeleteFileReques(selectedItems[0].getText());
										}
									}
								});
							}
							{
								downloadStartButton = new Button(composite1, SWT.PUSH | SWT.CENTER);
								FormData downloadStartButtonLData = new FormData();
								downloadStartButtonLData.left =  new FormAttachment(0, 1000, 24);
								downloadStartButtonLData.top =  new FormAttachment(0, 1000, 242);
								downloadStartButtonLData.width = 72;
								downloadStartButtonLData.height = 23;
								downloadStartButton.setLayoutData(downloadStartButtonLData);
								downloadStartButton.setText("Download");
								downloadStartButton.setEnabled(false);
								downloadStartButton.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										TreeItem[] selectedItems = fileDownloadTree.getSelection();
										if(selectedItems != null && selectedItems.length == 1){
											if(client.donwloadFile(selectedItems[0].getText())){
												MessageBox message = new MessageBox(getShell(),SWT.ICON_INFORMATION);
												message.setMessage("File downloaded successfully: "+selectedItems[0].getText());
												message.setText("Success");
												message.open();
											}else{
												MessageBox message = new MessageBox(getShell(),SWT.ICON_INFORMATION);
												message.setMessage("File download failed: "+selectedItems[0].getText());
												message.setText("Failure");
												message.open();
											}
										}
									}
								});
							}
							{
								FormData fileDownloadTreeLData = new FormData();
								fileDownloadTreeLData.left =  new FormAttachment(0, 1000, 12);
								fileDownloadTreeLData.top =  new FormAttachment(0, 1000, 12);
								fileDownloadTreeLData.width = 351;
								fileDownloadTreeLData.height = 205;
								fileDownloadTree = new Tree(composite1, SWT.NONE);
								fileDownloadTree.setLayoutData(fileDownloadTreeLData);
								fileDownloadTree.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										System.out.println("fileDownloadTree.widgetSelected, event="+evt);
										if(!evt.item.equals(rootNode)){
											downloadStartButton.setEnabled(true);
											updateFileButton.setEnabled(true);
											deleteFileButton.setEnabled(true);
										}else{
											downloadStartButton.setEnabled(false);
											updateFileButton.setEnabled(false);
											deleteFileButton.setEnabled(false);
										}
									}
								});
								{
									rootNode = new TreeItem(fileDownloadTree, SWT.NONE);
									rootNode.setText("File");
								}
								{
									TreeItem testItem = new TreeItem(rootNode, SWT.NONE);
									testItem.setText("Test");
									testItem.setExpanded(false);
								}
								rootNode.setExpanded(true);
							}
						}
					}
					{
						uploadFileTab = new TabItem(tabFolderComp, SWT.NONE);
						uploadFileTab.setText("Upload File");
						{
							uploadComp = new Composite(tabFolderComp, SWT.NONE);
							FormLayout uploadCompLayout = new FormLayout();
							uploadComp.setLayout(uploadCompLayout);
							uploadFileTab.setControl(uploadComp);
							{
								cancelUploadButton = new Button(uploadComp, SWT.PUSH | SWT.CENTER);
								FormData cancelUploadButtonLData = new FormData();
								cancelUploadButtonLData.left =  new FormAttachment(0, 1000, 153);
								cancelUploadButtonLData.top =  new FormAttachment(0, 1000, 242);
								cancelUploadButtonLData.width = 56;
								cancelUploadButtonLData.height = 23;
								cancelUploadButton.setLayoutData(cancelUploadButtonLData);
								cancelUploadButton.setText("Cancel");
								cancelUploadButton.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										tabFolderComp.setSelection(0);
									}
								});
							}
							{
								resetUploadButton = new Button(uploadComp, SWT.PUSH | SWT.CENTER);
								FormData resetUploadButtonLData = new FormData();
								resetUploadButtonLData.left =  new FormAttachment(0, 1000, 105);
								resetUploadButtonLData.top =  new FormAttachment(0, 1000, 242);
								resetUploadButtonLData.width = 48;
								resetUploadButtonLData.height = 23;
								resetUploadButton.setLayoutData(resetUploadButtonLData);
								resetUploadButton.setText("Reset");
								resetUploadButton.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										uploadProgressBar.setSelection(0);
										fileUploadLocation.setText("") ;
									}
								});
							}
							{
								uploadFileButton = new Button(uploadComp, SWT.PUSH | SWT.CENTER);
								FormData uploadFileButtonLData = new FormData();
								uploadFileButtonLData.left =  new FormAttachment(0, 1000, 43);
								uploadFileButtonLData.top =  new FormAttachment(0, 1000, 242);
								uploadFileButtonLData.width = 63;
								uploadFileButtonLData.height = 23;
								uploadFileButton.setLayoutData(uploadFileButtonLData);
								uploadFileButton.setText("Upload");
								uploadFileButton.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										uploadFileButtonWidgetSelected(evt);
									}
								});
							}
							{
								fileUploadBrowserButton = new Button(uploadComp, SWT.PUSH | SWT.CENTER);
								FormData fileUploadBrowserButtonLData = new FormData();
								fileUploadBrowserButtonLData.left =  new FormAttachment(0, 1000, 306);
								fileUploadBrowserButtonLData.top =  new FormAttachment(0, 1000, 144);
								fileUploadBrowserButtonLData.width = 47;
								fileUploadBrowserButtonLData.height = 23;
								fileUploadBrowserButton.setLayoutData(fileUploadBrowserButtonLData);
								fileUploadBrowserButton.setText("Browse");
								fileUploadBrowserButton.addSelectionListener(new SelectionAdapter() {
									public void widgetSelected(SelectionEvent evt) {
										if(fileDialog.getFileName().length() != 0){
											fileDialog.setFileName("");
										}								
										fileUploadLocation.setText(fileDialog.open());
									}
								});
							}
							{
								FormData fileUploadLocationLData = new FormData();
								fileUploadLocationLData.left =  new FormAttachment(0, 1000, 83);
								fileUploadLocationLData.top =  new FormAttachment(0, 1000, 116);
								fileUploadLocationLData.width = 264;
								fileUploadLocationLData.height = 18;
								fileUploadLocation = new Text(uploadComp, SWT.NONE);
								fileUploadLocation.setLayoutData(fileUploadLocationLData);
							}
							{
								uploadFileBrowse = new Label(uploadComp, SWT.NONE);
								FormData uploadFileBrowseLData = new FormData();
								uploadFileBrowseLData.left =  new FormAttachment(0, 1000, 8);
								uploadFileBrowseLData.top =  new FormAttachment(0, 1000, 116);
								uploadFileBrowseLData.width = 84;
								uploadFileBrowseLData.height = 18;
								uploadFileBrowse.setLayoutData(uploadFileBrowseLData);
								uploadFileBrowse.setText("Browse for File");
							}
							{
								progressUpdateBarLabel = new Label(uploadComp, SWT.NONE);
								FormData progressUpdateBarLabelLData = new FormData();
								progressUpdateBarLabelLData.left =  new FormAttachment(0, 1000, 8);
								progressUpdateBarLabelLData.top =  new FormAttachment(0, 1000, 30);
								progressUpdateBarLabelLData.width = 88;
								progressUpdateBarLabelLData.height = 13;
								progressUpdateBarLabel.setLayoutData(progressUpdateBarLabelLData);
								progressUpdateBarLabel.setText("Upload Progress : ");
							}
							{
								FormData uploadProgressBarLData = new FormData();
								uploadProgressBarLData.left =  new FormAttachment(0, 1000, 8);
								uploadProgressBarLData.top =  new FormAttachment(0, 1000, 52);
								uploadProgressBarLData.width = 345;
								uploadProgressBarLData.height = 17;
								uploadProgressBar = new ProgressBar(uploadComp, SWT.NONE);
								uploadProgressBar.setLayoutData(uploadProgressBarLData);
							}
						}
					}
					tabFolderComp.setSelection(0);
				}
			}
			{
				menu1 = new Menu(getShell(), SWT.BAR);
				getShell().setMenuBar(menu1);
				{
					fileMenuItem = new MenuItem(menu1, SWT.CASCADE);
					fileMenuItem.setText("File");
					{
						fileMenu = new Menu(fileMenuItem);
						{
							connentMenuItem = new MenuItem(fileMenu, SWT.PUSH);
							connentMenuItem.setText("Download Location");
							connentMenuItem.addSelectionListener(new SelectionAdapter() {
								public void widgetSelected(SelectionEvent evt) {
									folderDialog.setMessage("Select a Download Location");
									folderDialog.setText("Directory Browser");
									String text = folderDialog.open();
									System.out.println(text);
									client.setDestination(text);
									
								}
							});
						}
						{
							exitMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
							exitMenuItem.setText("Exit");
							exitMenuItem.addSelectionListener(new SelectionAdapter() {
								public void widgetSelected(SelectionEvent evt) {
									System.exit(0);
								}
							});
						}
						fileMenuItem.setMenu(fileMenu);
					}
				}
				{
					helpMenuItem = new MenuItem(menu1, SWT.CASCADE);
					helpMenuItem.setText("Help");
					{
						helpMenu = new Menu(helpMenuItem);
						{
							aboutMenuItem = new MenuItem(helpMenu, SWT.CASCADE);
							aboutMenuItem.setText("About");
							aboutMenuItem.addSelectionListener(new SelectionAdapter() {
								public void widgetSelected(SelectionEvent evt) {
									MessageBox message = new MessageBox(getShell(),SWT.ICON_INFORMATION);
									message.setMessage("This is the client for the Distributed File Store\nThe client should automatically connet and allow:\n*  File Upload\n*  File Download ");
									message.setText("About");
									message.open();
								}
							});
						}
						helpMenuItem.setMenu(helpMenu);
					}
				}
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void updateTreeFromModel(){
		Model model = this.client.getSystemModel();
		ResIterator iteratorOfFiles = model.listSubjectsWithProperty(FileItem.FILENAME);
		this.fileDownloadTree.removeAll();
		rootNode = new TreeItem(fileDownloadTree, SWT.NONE);
		rootNode.setText("File");
		rootNode.setExpanded(true);
		List<Resource> listOfFiles = iteratorOfFiles.toList();
		for(int i =0; i< listOfFiles.size(); i++){
			Resource res = listOfFiles.get(i);
			TreeItem testItem = new TreeItem(rootNode, SWT.NONE);
			testItem.setText(res.getProperty(FileItem.FILENAME).getString());
			testItem.setExpanded(false);
		}
	}
	public void handleGovenorStatus(String statusData) {
		System.out.println("Recieved an update");
		StringReader in = new StringReader(statusData);
		Model model = ModelFactory.createDefaultModel();
		model.read(in,"");
		this.client.setSystemModel(model);
		Display display = this.getDisplay() ;
		display.syncExec(
				  new Runnable() {
				    public void run(){
				    	updateTreeFromModel();
				    }
				  });

		
	}
	public void updateProgress(int percentage) {
		Display display = this.getDisplay() ;
		display.syncExec(
				  new Runnable() {
				    public void run(){
						uploadProgressBar.setSelection(33);
				    }
				  });

		
	}
	
	private void uploadFileButtonWidgetSelected(SelectionEvent evt) {
		System.out.println("uploadFileButton.widgetSelected, event="+evt);
		String filename = this.fileUploadLocation.getText();
		this.client.uploadFile(filename, this);
		//TODO add your code for uploadFileButton.widgetSelected
	}

	/**
	* Auto-generated main method to display this 
	* org.eclipse.swt.widgets.Composite inside a new Shell.
	*/


}
